package com.hopu.v1.controller.front.question;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hopu.v1.pojo.common.R;
import com.hopu.v1.pojo.question.CommentLikes;
import com.hopu.v1.pojo.question.QuestionsComments;
import com.hopu.v1.service.front.question.FCommentLikesService;
import com.hopu.v1.service.front.question.FQuestionsCommentsService;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1/front/commentLike")
public class FCommentLikeController {

    @Resource
    private FCommentLikesService commentLikesService;

    @Resource
    private FQuestionsCommentsService questionsCommentsService;

    /**
     * 点赞和取消点赞
     * @param studentId 学生id
     * @param commentId 点赞的评论id
     * @param isLike 是否已经点过赞
     * @return
     */
    @GetMapping
    @Transactional
    public R likeAndUnLike(String studentId,Integer commentId,Integer isLike){
        CommentLikes commentLikes = new CommentLikes();
        commentLikes.setCommentId(commentId);
        commentLikes.setStudentId(studentId);
        //进行点赞
        if (isLike == 0){
            //插入点赞数据
            commentLikesService.save(commentLikes);
            //对应的评论点赞数 +1
            UpdateWrapper<QuestionsComments> wrapper = new UpdateWrapper<>();
            wrapper.eq("id", commentId);
            wrapper.setSql(" likes = likes + 1");
            questionsCommentsService.update(wrapper);
            return R.ok("点赞成功",questionsCommentsService.query().select("likes").eq("id",commentId).one());
        }else {
            //取消点赞
            //删除点赞数据
            QueryWrapper<CommentLikes> wrapper = new QueryWrapper<>();
            wrapper.eq("comment_id", commentId).eq("student_id", studentId);
            commentLikesService.remove(wrapper);
            //对应的评论点赞数 -1
            UpdateWrapper<QuestionsComments> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", commentId);
            updateWrapper.setSql(" likes = likes - 1");
            questionsCommentsService.update(updateWrapper);
            return R.ok("取消点赞",questionsCommentsService.query().select("likes").eq("id",commentId).one());
        }
    }
}
